package com.wl.index.Controller;

import com.wl.entity.ChilderComments;
import com.wl.index.Biz.Impl.ChilderCommentsBizImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/childercomments")
public class ChilderCommentsController {
    @Autowired
    private ChilderCommentsBizImpl ccommentsBiz;

    //根据帖子id和父评论id获取子评论列表
    @GetMapping("/list")
    public ResponseEntity<List<ChilderComments>> getChilderCommentsByCid(
            @RequestParam Integer cid,@RequestParam Integer nid) {
        try{
            List<ChilderComments> ccomments = ccommentsBiz.getChilderCommentsByCid(cid,nid);
            return ResponseEntity.ok(ccomments);
        }catch (Exception e){
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }

    }

    //根据父评论id和帖子id获取子评论和用户信息
    @GetMapping("/listUser")
    public ResponseEntity<List<Map<String,Object>>> getCCommentsByUid(
            @RequestParam Integer cid,@RequestParam Integer nid){
        try{
            List<Map<String,Object>> ccomments = ccommentsBiz.getCCommentsByUid(cid,nid);
            return ResponseEntity.ok(ccomments);
        }catch (Exception e){
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    //添加子评论
    @PostMapping("/add")
    public ResponseEntity<?> addChilderComments(@RequestBody ChilderComments ccomments){
        System.out.println("接收到的子评论数据：" + ccomments);
        try{
            // 2. 检查必要字段
            if (ccomments.getContext() == null || ccomments.getCid() == 0 || ccomments.getUid() == 0 ||ccomments.getNid() == 0) {
                return ResponseEntity.badRequest().body("缺少必要参数");
            }

            // 3. 确保日期字段处理正确
            if (ccomments.getCreatAt() == null) {
                ccomments.setCreatAt(new Date());
            }
            int result = ccommentsBiz.addChilderComments(ccomments);
            if (result > 0){
                return ResponseEntity.ok("添加评论成功");
            }else {
                return ResponseEntity.badRequest().body("评论添加失败");
            }
        }catch (IllegalArgumentException e){
            return ResponseEntity.badRequest().body(e.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器内部错误");
        }

    }

}
